#%%
from DataGeter import aksharePack, tusharePack
import pandas as pd
import datetime
import time
import os

# %%


class GetTradeDays(object):
    def __init__(self, MainPath=r"D:/StockDatas/", subPath=r"basic/"):
        """
        GetTradeDays(path=r"D:/StockDatas/").run()
        多态可修改这部分内容
        ```python
        def __init__(self, path=r"D:/StockDatas/", subPath=r"basic/"):
            self.path = path + subPath
            self.filename = r"trade_days_{}.csv".format(str(datetime.date.today()))
        def dataGeter(self):
            temp = pd.DataFrame(tusharePack.TradeDays())
            return temp
        def dataGeter
        def DirPathChick
        def FileChack
        def pathrefrom
        def AutoRmove
        def LoadFile
        def run
        ```
        + 可以输入path pathname
        + 注意path使用路径不要精确到保存位置
        + name为 r"trade_days{}.csv".format(str(datetime.date.today()))
        """
        self.path = MainPath + subPath
        self.filename = r"trade_days_{}.csv".format(str(datetime.date.today()))

    def dataGeter(self):
        """
        便于继承
        """
        temp = pd.DataFrame(tusharePack.TradeDays())
        return temp

    def DirPathChick(self, new_paths):
        """
        检查文件夹是否存在，不存在新建
        """
        if os.path.isdir(new_paths) and os.path.exists(new_paths):
            pass
        else:
            os.makedirs(new_paths)

    def FileChack(self, new_paths):
        """
        检查文件是否存在
        """
        # print(new_paths)
        if os.path.isfile(new_paths) and os.path.exists(new_paths):
            return True
        return False

    def pathrefrom(self, path):
        self.DirPathChick(self.path)
        paths = self.path + self.filename
        return paths

    def AutoRmove(self):
        """
        删除历史文件
        """
        dirl = os.listdir(self.path)
        st = self.filename
        st = st.split("_")
        if len(st) > 1:
            st = st[-1]
            for dirs in dirl:
                if dirs.endswith(st):
                    pass
                else:
                    di = self.path + dirs
                    print("{}==>  removed {} not meching".format(di, st))
                    os.remove(di)
        else:
            print("not matching")

    def LoadFile(self, path):
        """
        总程序
        路径检查,文件检查,删除历史文件
        """
        path = self.pathrefrom(path)
        if self.FileChack(path):
            data = pd.read_csv(path)
            # print("load => {}".format(path))
            return data
        else:
            self.AutoRmove()
            data = self.dataGeter()
            data.to_csv(path, index=False)
            print("save => {}".format(path))
            return data

    def run(self):
        data = self.LoadFile(self.path)
        return data


class GetStockList(GetTradeDays):
    def __init__(self, MainPath, subPath):
        """
        GetStockList(path=r"D:/StockDatas/").run()
        """
        super(GetStockList, self).__init__(
            MainPath=r"D:/StockDatas/", subPath=r"basic/"
        )
        self.path = MainPath + subPath
        self.filename = r"stock_data_{}.csv".format(str(datetime.date.today()))

    def dataGeter(self):
        temp = pd.DataFrame(tusharePack.getStockList())
        df = aksharePack.Divided_detial_total()
        if df.shape[0] > 1:
            temp = self.formating(temp, df)
        return temp

    def formating(self, df1, df2):
        df2 = df2.drop("详细", axis=1)
        dic = {
            "代码": "code",
            "名称": "akname",
            "上市日期": "list_date",
            "累计股息(%)": "total_divident",
            "年均股息(%)": "divident_pre_year",
            "分红次数": "divident_times",
            "融资总额(亿)": "total_funding",
            "融资次数": "funding_times",
        }
        df2 = df2.rename(columns=dic)
        df1["code"] = df1.ts_code.apply(lambda x: str(x).split(".")[0])
        df1_col = df1.columns.tolist()
        df1_col.remove("list_date")
        df1 = df1[df1_col]

        df2 = df2[
            [
                "code",
                "total_divident",
                "divident_pre_year",
                "divident_times",
                "total_funding",
                "funding_times",
                "list_date",
            ]
        ]
        df1 = pd.merge(df1, df2, on="code")
        df1 = df1.drop("code", axis=1)
        return df1

    def run(self):
        data = self.LoadFile(self.path)
        return data


# class GetHistoryBar(GetTradeDays):
#     def __init__(self, code, path=r"D:/StockDatas/", dirName="163_Daily_Bar"):
#         super(GetStockList, self).__init__(path=r"D:/StockDatas/")
#         self.code = code
#         self.path = path + dirName + "/"
#         self.dirName = dirName
#         self.filename = r"{}_{}.csv".format(code, str(datetime.date.today()))

#     def dataGeter(self):
#         DailyBar = Get_163DailyBar.Daily163().run()
#         df = pd.DataFrame(self.code, area, starttime, header, path=r"D:/StockDatas/")


#%%
class RealTimeticker(GetTradeDays):
    def __init__(
        self, timmer, code="601398", MainPath=r"D:/StockDatas/", subPath=r"daily/"
    ):
        """
        获取实时股票信息
        ```python
        code = "600010"
        timmer = time.localtime().tm_min
        RealTimeticker(timmer, code).run()
        def __init__(self, timmer, code="601398", path=r"D:/StockDatas/", subPath= r"daily/"):
            super(RealTimeticker, self).__init__(path=r"D:/StockDatas/", subPath= r"daily/")
            self.path = path + subPath
            self.filename = code + "_ticker_daily" + r".csv"
            self.code = code
            self.T2 = timmer
        ```
        """
        super(RealTimeticker, self).__init__(
            MainPath=r"D:/StockDatas/", subPath=r"daily/"
        )
        self.path = MainPath + subPath
        self.filename = code + "_ticker_daily" + r".csv"
        self.code = code
        self.T2 = timmer

    def dataGeter(self):
        for mode in range(2):
            if mode == 0:
                df = pd.DataFrame(tusharePack.todays_ticks(self.code))
            elif mode == 1:
                df = tusharePack.todays_ticks(code)
            if df.shape[0] > 1:
                return df

    def LoadFile(self):
        path = self.path + self.filename
        if self.FileChack(path):
            df = pd.read_csv(path)
            return df
        else:
            print("file not found")
            return pd.DataFrame()

    def Timmer(self):
        """
        计时器,如果时钟没有清零,
        """
        T1 = time.localtime().tm_min
        if self.T2 - T1 < -5:
            self.T2 = time.localtime().tm_min
            print("pass")
            return True
        else:
            print("{} mins left".format(str(self.T2 - T1 + 5)))
            return False

    def singe_ticker(self):
        try:
            df = self.dataGeter()
            return df
        except Exception as e:
            print(e)
            self.LoadFile()
            return pd.DataFrame()

    def formating(self, df):
        df.time = df.time.apply(
            lambda x: str(datetime.datetime.today()).split(" ")[0]
            + " "
            + str(x)[:2]
            + ":"
            + str(x)[2:4]
            + ":"
            + str(x)[-2:]
        )
        df["code"] = "'" + self.code
        path = self.path + self.filename
        df.to_csv(path, index=False)
        return df

    def run(self):
        self.DirPathChick(self.path)
        if self.Timmer():
            df = self.singe_ticker()
            try:
                df = self.formating(df)
            except Exception as e:
                print(e)
        else:
            df = self.LoadFile()
        return df


# class
#%%
if __name__ == "__main__":
    GetStockList(MainPath=r"D:/StockDatas/").run()
    GetTradeDays(MainPath=r"D:/StockDatas/").run()


# def TopAnalysit():
#     """
#     排名前五的交易员信息
#     analysitInfor().TopAnalysit()
#     """
#     df = aksharePack.analysit()
#     tdf = pd.DataFrame()
#     for key in df.columns.tolist()[4:7]:
#         _df = df.sort_values(by=key).iloc[0:5]
#         tdf = pd.concat([tdf, _df])
#     tdf = tdf.drop_duplicates(subset=["分析师名称"])
#     tdf = tdf.drop("序号", axis=1)
#     return tdf


# def Top5StockHolding():
#     """
#     排名前五的交易员持股详情
#     analysitInfor().Top5StockHolding()
#     """
#     df = TopAnalysit()
#     IDl = df.loc[:, "分析师ID"].tolist()
#     tdf = pd.DataFrame()
#     for idd in IDl:
#         print(idd)
#         _df = aksharePack.akAnalystDetail(idd)
#         _df["分析师ID"] = idd
#         tdf = pd.concat([tdf, _df])
#     tdf = tdf.join(df.set_index("分析师ID"), on="分析师ID", how="inner")
#     return tdf


#%%